package com.txtsqlclient.ui.helper;

/**
 * This class attempts to erase characters echoed to the console. Refer to this page for more
 * details: http://java.sun.com/developer/technicalArticles/Security/pwordmask/
 */

class MaskingThread extends Thread {

	private volatile boolean mask = true;

	private static final char ECHO_CHAR = '*';

	/**
	 * @param prompt
	 *            The prompt displayed to the user
	 */
	public MaskingThread(final String prompt) {
		System.out.print(prompt);
	}

	/**
	 * Begin masking until asked to stop.
	 */
	@Override
	public void run() {

		final int priority = Thread.currentThread().getPriority();
		Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

		try {
			this.mask = true;
			while (this.mask) {
				System.out.print("\010" + ECHO_CHAR);
				// attempt masking at this rate
				Thread.currentThread().sleep(1);
			}
		} catch (InterruptedException iex) {
			Thread.currentThread().interrupt();
			return;
		} finally { // restore the original priority
			Thread.currentThread().setPriority(priority);
		}
	}

	/**
	 * Instruct the thread to stop masking.
	 */
	public void stopMasking() {
		this.mask = false;
	}

	public void startMasking() {
		this.mask = true;
	}
}